package com.example.blog.restController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.base.BaseImpl;
import com.example.blog.entity.Query;
import com.example.blog.entity.User;
import com.example.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class UserListController {

    @Autowired
    BaseImpl baseImpl;

    @Autowired
    UserService userService;

    //    get和post传参时不一样：
    //    get前端需要使用params进行传参，后动不需要添加requestbody注解
    //    post前端不需要params进行传参，后端需要添加requestbody注解
    @GetMapping("/userList")
    public Map<String, Object> userList(Query query) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Page listByQueryPage = baseImpl.getListByQueryPage(userService, query);
            long total = listByQueryPage.getTotal();
            List<User> userList = listByQueryPage.getRecords();
            map.put("code", 200);
            map.put("message", "获取成功！");
            map.put("data", userList);
            map.put("total", total);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
            map.put("message", "获取失败！");
        }
        return map;
    }

    @GetMapping("/updateUserState")
    public Map<String, Object> updateUserState(User user) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            baseImpl.updateByEntity(userService, user);
            map.put("code", 200);
            map.put("message", "修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
            map.put("message", "修改失败！");
        }
        return map;
    }

    @PostMapping("/addUser")
    public Map<String, Object> addUser(@RequestBody User user) {
        HashMap<String, Object> map = new HashMap<>();
        try {
//            添加默认信息
            user.setCreateTime(new Date());
            user.setSex("男");
            user.setState(0);
            baseImpl.insertByEntity(userService, user);
            map.put("code", 200);
            map.put("message", "添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
            map.put("message", "添加失败！");
        }
        return map;
    }
}
